package com.itheima.algorithm.priorityqueue;

import com.itheima.algorithm.leetcode.ListNode;

/**
 * @author: TylerZhong
 * @description:
 */
public class MinHeap {
    private int size;
    private ListNode[] array;


    public MinHeap(int capacity) {
        array = new ListNode[capacity];
    }

    public boolean offer(ListNode offered) {
        if (isFull()) {
            return false;
        }
        int child = size++;
        int parent = (child - 1) / 2;
        while (child > 0 && offered.val < array[parent].val) {
            array[child] = array[parent];
            child = parent;
            parent = (child - 1) / 2;
        }
        array[child] = offered;
        return true;
    }

    /**
     * 1. 交换堆顶和尾部元素，让尾部元素出队
     * 2. （下潜）
     *      - 从堆顶开始，将父元素与两个孩子较大者交换
     *      - 直到父元素大于两个孩子，或没有孩子为止
     * @return
     */
    public ListNode poll() {
        if (isEmpty()) {
            return null;
        }
        swap(0, size-1);
        ListNode listNode = array[--size];
        array[size] = null; // help GC
        // 下潜
        down(0);
        return listNode;
    }

    public void down(int parent) {
        int left = 2 * parent + 1;
        int right = left + 1;
        int min = parent; // 假设父元素优先级最高
        if (left < size && array[min].val > array[left].val) {
            min = left;
        }
        if (right < size && array[min].val > array[right].val) {
            min = right;
        }
        if (min != parent) { // 有孩子比父亲大
            swap(parent, min);
            down(min);
        }
    }

    public void swap(int i, int j) {
        ListNode temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == array.length;
    }
}
